<?php

define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid();
$wechatObj->responseMsg();

class wechatCallbackapiTest {

    private $apikey = '54cce520c6b71080fab6931fd29d9936';
    private $apisecret = '8isrmu0jtboc';

    public function valid() {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg() {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)) {

            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            switch ($RX_TYPE) {
                case "text":
                    $resultStr = $this->handleText($postObj);
                    break;
                case "event":
                    $resultStr = $this->handleEvent($postObj);
                    break;
                default:
                    $resultStr = "Unknow msg type: " . $RX_TYPE;
                    break;
            }
            echo $resultStr;
        } else {
            echo "";
            exit;
        }
    }

    public function handleText($Obj) {
        $keyword = $Obj->Content;
        if (!empty($keyword)) {
            $translate1 = mb_substr($keyword, 0, 2, "UTF-8");
            $translate2 = mb_substr($keyword, 2, 1000, "UTF-8");
            if ($translate1 == "翻译" && !empty($translate2)) {
                $contentStr = $this->youdaoDic($translate2);
                //   $contentStr = $this->youdaoDic($str_key);
            } else if ($keyword == '笑话') {
                $contentStr = $this->xiaohua();
            } else if ($keyword == '月老灵签') {
                $contentStr = $this->yuelao();
            } else if ($keyword == '观音灵签') {
                $contentStr = $this->guanyin();
            } else if ($keyword == '财神爷灵签') {
                $contentStr = $this->guanyin();
            } else if ($reply = $this->huifu($keyword)) {
                $contentStr = $reply;
            } else {
                $contentStr = $this->xiaoJ($keyword);
            }
            $resultStr = $this->responseText($Obj, $contentStr);
            echo $resultStr;
        } else {
            echo "并没有什么东西哦";
        }
    }

    public function handleEvent($object) {
        $contentStr = "";
        switch ($object->Event) {
            case "subscribe":
                $contentStr = "感谢关注江灵助手。可以回复以下内容实现相应功能（请回复中文）:\n1.回复翻译+你想要翻译的内容可以进行翻译哦（例如发送：翻译我爱你，即可收到I love you）。\n2.天气查询功能（城市+天气，如广州天气）。\n3.lol战绩\n4.成语接龙（每次接龙均回复@cy+成语）\n5.笑话\n6.抽签(回复月老灵签、观音灵签或者财神爷灵签)。\n7.手机号查询（@sjh+你要查询的号码）\n8.随便回，跟我进行聊天\n9.其他功能更待开发哦，感谢你来支持我！";
                break;
            default :
                $contentStr = "Unknow Event: " . $object->Event;
                break;
        }
        $resultStr = $this->responseText($object, $contentStr);
        return $resultStr;
    }

    public function responseText($object, $content, $flag = 0) {
        $textTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[text]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					<FuncFlag>%d</FuncFlag>
					</xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }

    private function checkSignature() {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    public function youdaoDic($word) {  //有道翻译接口
        $keyfrom = "weatherhelper";
        $apikey = "2125365086";
        $word = urlencode($word);
        $url_youdao = 'http://fanyi.youdao.com/fanyiapi.do?keyfrom=' . $keyfrom . '&&key=' . $apikey . '&&type=data&doctype=xml&&version=1.1&&q=' . $word;
        $xmlStyle = simplexml_load_file($url_youdao);
        $errorCode = $xmlStyle->errorCode;
        $paras = $xmlStyle->translation->paragraph;
        if ($errorCode == 0) {
            return $paras;
        } else if ($errorCode == 20) {
            return "要翻译的文本过长";
        } else if ($errorCode == 30) {
            return "无法进行有效的翻译";
        } else if ($errorCode == 40) {
            return "不支持的语言类型";
        } else if ($errorCode == 50) {
            return "无法进行有效的翻译";
        } else if ($errorCode == 60) {
            return "无词典结果，仅在获取词典结果生效";
        }
    }

    public function huifu($word) {
        $reply = array(
            '你好' => '你好呀，欢迎关注我，我是你的智能助手，回复“帮助”可以获得我的使用说明哦！',
            '燕燕' => '燕儿专属！么么哒',
            '龙燕' => '燕儿专属！么么哒',
            '抽签' => '在我这里可以抽取观音灵签、月老灵签和财神爷灵签哦。',
            '帮助' => "可以回复以下内容实现相应功能（请回复中文）:\n1.回复翻译+你想要翻译的内容可以进行翻译哦（例如发送：翻译我爱你，即可收到I love you）。\n2.天气查询功能（城市+天气，如广州天气）。\n3.lol战绩\n4.成语接龙（每次接龙均回复@cy+成语）\n5.笑话\n6.抽签(回复月老灵签、观音灵签或者财神爷灵签)。\n7.手机号查询（@sjh+你要查询的号码）\n8.随便回，跟我进行聊天\n9.其他功能更待开发哦，感谢你来支持我！",
            '说明' => "可以回复以下内容实现相应功能（请回复中文）:\n1.回复翻译+你想要翻译的内容可以进行翻译哦（例如发送：翻译我爱你，即可收到I love you）。\n2.天气查询功能（城市+天气，如广州天气）。\n3.lol战绩\n4.成语接龙（每次接龙均回复@cy+成语）\n5.笑话\n6.抽签(回复月老灵签、观音灵签或者财神爷灵签)。\n7.手机号查询（@sjh+你要查询的号码）\n8.随便回，跟我进行聊天\n9.其他功能更待开发哦，感谢你来支持我！",
            '使用说明' => "可以回复以下内容实现相应功能（请回复中文）:\n1.回复翻译+你想要翻译的内容可以进行翻译哦（例如发送：翻译我爱你，即可收到I love you）。\n2.天气查询功能（城市+天气，如广州天气）。\n3.lol战绩\n4.成语接龙（每次接龙均回复@cy+成语）\n5.笑话\n6.抽签(回复月老灵签、观音灵签或者财神爷灵签)。\n7.手机号查询（@sjh+你要查询的号码）\n8.随便回，跟我进行聊天\n9.其他功能更待开发哦，感谢你来支持我！",
            '怎么用' => "可以回复以下内容实现相应功能（请回复中文）:\n1.回复翻译+你想要翻译的内容可以进行翻译哦（例如发送：翻译我爱你，即可收到I love you）。\n2.天气查询功能（城市+天气，如广州天气）。\n3.lol战绩\n4.成语接龙（每次接龙均回复@cy+成语）\n5.笑话\n6.抽签(回复月老灵签、观音灵签或者财神爷灵签)。\n7.手机号查询（@sjh+你要查询的号码）\n8.随便回，跟我进行聊天\n9.其他功能更待开发哦，感谢你来支持我！",
            '你能做什么' => "可以回复以下内容实现相应功能（请回复中文）:\n1.回复翻译+你想要翻译的内容可以进行翻译哦（例如发送：翻译我爱你，即可收到I love you）。\n2.天气查询功能（城市+天气，如广州天气）。\n3.lol战绩\n4.成语接龙（每次接龙均回复@cy+成语）\n5.笑话\n6.抽签(回复月老灵签、观音灵签或者财神爷灵签)。\n7.手机号查询（@sjh+你要查询的号码）\n8.随便回，跟我进行聊天\n9.其他功能更待开发哦，感谢你来支持我！",
        );
        if (!empty($reply["$word"])) {
            return $reply["$word"];
        } else {
            return false;
        }
    }

    public function xiaoJ($word) {
        $url = 'http://i.itpk.cn/api.php?question=' . $word . '&api_key=' . $this->apikey . '&api_secret=' . $this->apisecret;
        return file_get_contents($url);
    }

    public function yuelao() {
        $url = 'http://i.itpk.cn/api.php?question=月老灵签&api_key=' . $this->apikey . '&api_secret=' . $this->apisecret;
        $content = file_get_contents($url);
        $content = json_decode($content);
        if (!empty($content)) {
            $map = '您抽取的是第%s签
签位：%s
签语：%s
注释：%s
解签：%s
白话释义：%s';
            return sprintf($map, $content->number1, $content->haohua, $content->shiyi, $content->zhushi, $content->jieqian, $content->baihua);
        } else {
            return '抱歉，什么都没抽到';
        }
    }

    public function guanyin() {
        $url = 'http://i.itpk.cn/api.php?question=观音灵签&api_key=' . $this->apikey . '&api_secret=' . $this->apisecret;
        $content = file_get_contents($url);
        $content = json_decode($content);
        $map = '您抽取的是第%s签
签位：%s
签语：%s
诗意：%s
解签：%s';
        if (!empty($content)) {
            return sprintf($map, $content->number1, $content->haohua, $content->qianyu, $content->shiyi, $content->jieqian);
        } else {
            return '抱歉，什么都没抽到';
        }
    }

    public function caishenye() {
        $url = 'http://i.itpk.cn/api.php?question=财神爷灵签&api_key=' . $this->apikey . '&api_secret=' . $this->apisecret;
        $content = file_get_contents($url);
        $content = json_decode($content);
        $map = '您抽取的是第%s签
签语：%s
注释：%s
解签：%s
解说：%s';
        if (!empty($content)) {
            return sprintf($map, $content->number1, $content->qianyu, $content->zhushi, $content->jieqian, $content->jieshuo);
        } else {
            return '抱歉，什么都没抽到';
        }
    }

    public function xiaohua() {
        $url = 'http://i.itpk.cn/api.php?question=笑话&api_key=' . $this->apikey . '&api_secret=' . $this->apisecret;
        $content = file_get_contents($url);
        $content = json_decode($content);
        $map ="题目：%s\n正文：%s";
        if (!empty($content)) {
            return sprintf($map, $content->title, $content->content);
        } else {
            return '抱歉，什么都没有';
        }
    }

}

?>